def recursion(data, pid=0, level=0, p_key='pid', c_key="children", i_key="id", callable=None):
    list = []
    for v in data:
        if v[p_key] == pid:
            v['level'] = level
            v[c_key] = recursion(data, v[i_key], level + 1, p_key, c_key, i_key, callable)
            if callable:
                v = callable(v, data)
            list.append(v)
    return list


def tree_recursion(data, pid=0, level=1, p_key="pid", i_key='id', _callable=None):
    _treeList = []

    def _tree_recursion(_data, _pid=0, _level=1, _p_key="pid", _i_key='id', _callable=None):
        for v in _data:
            if v[_p_key] == _pid:
                v['level'] = _level
                if _callable:
                    v = _callable(v, _data)
                _treeList.append(v)
                _tree_recursion(_data, v[_i_key], _level + 1, _p_key, _i_key, _callable)

        return _treeList

    return _tree_recursion(data, pid, level, p_key, i_key, _callable)

# ps: id 不能为 0
test_data = [
    {"id": 1, "pid": 0, "title": "test"},
    {"id": 2, "pid": 1, "title": "test"},
    {"id": 3, "pid": 2, "title": "test"},
    {"id": 4, "pid": 2, "title": "test"},
    {"id": 5, "pid": 2, "title": "test"},
    {"id": 6, "pid": 0, "title": "test"},
    {"id": 7, "pid": 0, "title": "test"},
    {"id": 8, "pid": 0, "title": "test"},
    {"id": 9, "pid": 0, "title": "test"},
    {"id": 10, "pid": 0, "title": "test"},
]

print("sorted")
# sorted 排序
for x in sorted(test_data, key=lambda e: e['id'], reverse=True):
    print(x)

print("recursion")
# recursion 递归
for x in recursion(test_data):
    print(x)

print("tree_recursion")
# recursion 递归
for x in tree_recursion(test_data):
    print(x)

print("tree_recursion 1")
# recursion 递归数组查找前对象
for x in tree_recursion(test_data, 1):
    print(1, x)